#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>

std::string getIpAddress() {
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    const char* kGoogleDnsIp = "8.8.8.8";
    int port = 53;
    
    struct sockaddr_in serv;
    memset(&serv, 0, sizeof(serv));
    serv.sin_family = AF_INET;
    serv.sin_addr.s_addr = inet_addr(kGoogleDnsIp);
    serv.sin_port = htons(port);

    connect(sock, (struct sockaddr*)&serv, sizeof(serv));
    
    struct sockaddr_in name;
    socklen_t namelen = sizeof(name);
    getsockname(sock, (struct sockaddr*)&name, &namelen);

    char buffer[100];
    const char* p = inet_ntop(AF_INET, &name.sin_addr, buffer, 100);

    close(sock);

    if(p != NULL) {
        return std::string(p);
    } else {
        return "";
    }
}

int main() {
    std::string ip = getIpAddress();

    if(ip.empty()) {
        std::cerr << "Error: Unable to retrieve IP address" << std::endl;
    } else {
        std::cout << "Your IP Address is: " << ip << std::endl;
    }

    return 0;
}
